using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TodoistClient
{
    public partial class Form1 : Form
    {
        long _editID = -1;
        TodoIstEngine _engine = new TodoIstEngine();
        Timer _refreshTimer = new Timer();
        bool _tokenset = false;
        public Form1()
        {
            InitializeComponent();
            DoInitialChecks();

            this.ShowInTaskbar=false;
            _refreshTimer.Interval = Properties.Settings.Default.RefreshInterval * 1000;
            _refreshTimer.Enabled = true;
            SetupData();
            this.Load += new EventHandler(Form1_Load);
            HideEditPanel();

        }

        private void DoInitialChecks()
        {
            if (Properties.Settings.Default.Token!=null && Properties.Settings.Default.Token == string.Empty)
            {
                while (true)
                {
                    MessageBox.Show("You must enter your ToDoist token before you can use the Todoist Desktop Client \r\nYou can get your unique token from the preferensces page on http://todoist.com", "No Token Set", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    TokenEntry __frm = new TokenEntry();
                    __frm.ShowDialog();
                    if (Properties.Settings.Default.Token == string.Empty)
                    {
                        MessageBox.Show("You must enter your ToDoist token before you can use the Todoist Desktop Client \r\nYou can get your unique token from the preferensces page on http://todoist.com", "No Token Set", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        _tokenset = true;
                        break;
                    }
                }
            }
            else
                _tokenset = true;
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            if (Properties.Settings.Default.MinimizeToTray)
            {
                e.Cancel = true;
                this.Hide();
            }
            base.OnClosing(e);
        }

        void Form1_Load(object sender, EventArgs e)
        {
            if (listBox1.Items.Count > 0)
            {
                listBox1.SelectedIndex = -1;
                listBox1.SelectedIndex = 0;
            }
            notifyIcon1.BalloonTipTitle = "ToDoist Info";
            
            int __icount = 0;
            foreach (object var in listBox1.Items)
            {
                __icount += ((Project)var).Items.Count;
            }
            notifyIcon1.BalloonTipText = "Projects: " + listBox1.Items.Count + Environment.NewLine+"Total Tasks:" +__icount.ToString();
            notifyIcon1.ShowBalloonTip(2000);
        }

        private void SetupData()
        {
            if (_tokenset)
            {
                _engine.password = Properties.Settings.Default.Token;
                _engine.RefreshDataFromService();
                listBox1.DataSource = _engine.Projects;
                listBox1.DisplayMember = "Name";
                listBox1.ValueMember = "ID";
            }
            
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_tokenset)
            {
                listView1.Items.Clear();
                if (listBox1.SelectedValue is long)
                {
                    Project __p = (Project)listBox1.SelectedItem;
                    long __id = (long)listBox1.SelectedValue;

                    foreach (TaskItem __item in __p.Items)
                    {
                        ListViewItem __itm = new ListViewItem(__item.Content);
                        __itm.Tag = __item;
                        if (!__item.Completed || (__item.Completed && _showCompleted))
                            listView1.Items.Add(__itm);
                    }
                    lblProjName.Text = __p.Name;
                    lblProjName.BackColor = __p.Color;
                }
            }
        }
        bool _showCompleted = true;
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            _showCompleted = checkBox1.Checked;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            lblProject.Text = listBox1.Text;
            button1.Enabled = false;
            _editID = -1;
            chkCompleted.Visible = false;
            ShowEditPanel();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (_editID != -1)
            {
                _engine.UpdateItem(_editID, textBox1.Text, dateTimePicker1.Value, 1);

                if (_completedChanged && chkCompleted.Checked)
                {
                    _engine.UpdateItemChecked(_editID, true);
                }
            }
            else
                _engine.AddItem((long)listBox1.SelectedValue, textBox1.Text, DateTime.Now, 1);
            SetupData();
            HideEditPanel();
            
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            Project __p = (Project)listBox1.SelectedItem;
            StringBuilder __s = new StringBuilder();
            __s.Append("Name:"+__p.Name + Environment.NewLine);
            __s.Append("UserID:" + __p.UserID.ToString() + Environment.NewLine);
            __s.Append("Color:" + __p.Color.ToString() + Environment.NewLine);
            __s.Append("Collapsed:" + __p.Collapsed.ToString() + Environment.NewLine);
            __s.Append("Order:" + __p.Order.ToString() + Environment.NewLine);
            __s.Append("Indent:" + __p.Indent.ToString() + Environment.NewLine);
            __s.Append("Cache Count:" + __p.CacheCount.ToString() + Environment.NewLine);

            MessageBox.Show(__s.ToString());
        }

        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (_tokenset)
            {
                Project __p = (Project)listBox1.Items[e.Index];
                SolidBrush __b = new SolidBrush(__p.Color);

                e.Graphics.FillRectangle(__b, e.Bounds);
                e.Graphics.DrawString(__p.Name, e.Font, new SolidBrush(listBox1.ForeColor), e.Bounds.X, e.Bounds.Y);
                e.DrawFocusRectangle();
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count==1)
            {
                TaskItem __task = (TaskItem)listView1.SelectedItems[0].Tag;
                _editID = __task.ID;
                textBox1.Text = __task.Content;
                chkCompleted.Checked = __task.Completed;
                ShowEditPanel();
                chkCompleted.Visible = true;
            }
        }
        private void ShowEditPanel()
        {
            button1.Enabled = false;
            pnlEdit.Visible = true;
            this.Width = 808;
        }
        private void HideEditPanel()
        {
            textBox1.Text = "";
            button1.Enabled = true;
            pnlEdit.Visible = false;
            this.Width = 581;
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            HideEditPanel();
        }

        private void chkCompleted_CheckedChanged(object sender, EventArgs e)
        {
            _completedChanged = true;
        }
        bool _completedChanged = false;

        private void button3_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Not Yet Implemented");
            _engine.DeleteItem(_editID);
            SetupData();
            HideEditPanel();
            
        }
    }
}